import React, { useEffect, useState } from "react";
import NavBarAgain from "../components/NavBarAgain";
import { Form,Button,Input,Toast,Popup } from 'antd-mobile'
import { connect } from 'react-redux'
import './Login.less'
import ButtonAgain from "../components/ButtonAgain";
import * as api from '../api/index'
import _ from '../assets/utils'
import action from '../store/action'

const validate = {
    phone(_,value){
        value = value.trim()
        let reg = /^(?:(?:\+|00)86)?1\d{10}$/
        if(value.length === 0) return Promise.reject(new Error('手机号是必填的')) 
        if(!reg.test(value)) return Promise.reject(new Error('手机号格式有误')) 
        return Promise.resolve()
    },
    code(_,value){
        value = value.trim()
        let reg = /^\d{6}$/
        if(value.length === 0) return Promise.reject(new Error('验证码是必填的')) 
        if(!reg.test(value)) return Promise.reject(new Error('验证码格式有误')) 
        return Promise.resolve()
    }
}
const Login = function Login(props){
    let { queryUserInfoAsync,navigate,usp } = props
    const [disabled,setDisabled] = useState(false),
        [sendText,setSendText] = useState('发送验证码'),
        [visible,setVisible] = useState(false),
        [verificationCode,setVerificationCode] = useState(0)
        /* [sendLoading,setSendLoading] = useState(false),
        [submitLoading,setSubmitLoading] = useState(false) */
    const [formIns] = Form.useForm()
    //let verificationCode
    const submit = async ()=>{
        try{
            /* 需手动处理 */
            await formIns.validateFields()
            let { phone,code } = formIns.getFieldsValue() 
            let {code:codeHttp,token} = await api.login(phone,code)
            if(+codeHttp !== 0){
                Toast.show({
                    icon:'fail',
                    content:'发送失败'
                })
                formIns.resetFields(['code'])
                return;
            }
            _.storage.set('tk',token)
            await queryUserInfoAsync() 
            Toast.show({
                icon:'success',
                content:'登录/注册成功'
            })
            let to = usp.get('to')
            to ? navigate(to,{ replace:true }) : navigate(-1)
        }catch(e){}
        
    }

    let timer = null, num = 31
    const countdown = ()=>{
        num--;
        if(num === 0){
            clearInterval(timer)
            timer = null
            setSendText('发送验证码')
            setDisabled(false)
            return
        }
        setSendText(`${num}秒后重发`)
    }
    const send = async ()=>{
        try{
            await formIns.validateFields(['phone']) 
            let phone = formIns.getFieldValue('phone')
            let { code,vCode } = await api.sendPhoneCode(phone)
            if(+code !== 0){
                Toast.show({
                    icon:'fail',
                    content:'发送失败'
                })
                return;
            }
            setDisabled(true)
            countdown()
            if(!timer) timer = setInterval(countdown,1000)
            setTimeout(()=>{
                setVisible(true)
                setVerificationCode(vCode)
            },1000)
        }catch(e){}
    }
    useEffect(()=>{
        return ()=>{
            if(timer){
                clearInterval(timer)
                timer = null
            }
        }
    },[])

    return <div className="login-box">
        <NavBarAgain  title='登录/注册' />
        <Form layout="horizontal" style={{'--border-top':'none'}} //onFinish={submit} 
            form={formIns}
            initialValues={{phone:'',code:''}}
            requiredMarkStyle={false} //使校验规则的*没有
            // footer={<Button type="submit" color="primary" loading={submitLoading}>提交</Button>}
            footer={<ButtonAgain color="primary" onClick={submit}>提交</ButtonAgain>} //删除type="submit"
        >
            <Form.Item name='phone' label='手机号' rules={[{validator:validate.phone}]}>
                <Input placeholder="请输入手机号" />   
            </Form.Item>
            <Form.Item name='code' label='验证码' 
                //rules={[{validator:validate.code}]}
                rules = {[{required:true,message:'验证码是必填项'},{pattern:/^\d{6}$/,message:'验证码格式错误'}]} //使用自带的内置规则
                //extra={<Button size="small" color="primary" onClick={send} disabled={disabled} loading={sendLoading}>{sendText}</Button>}
                extra={<ButtonAgain size="small" color="primary" onClick={send}
                    disabled={disabled}
                >
                    {sendText}
                </ButtonAgain>}
            >
                <Input placeholder="请输入验证码" />   
            </Form.Item>
        </Form>
        <Popup visible={visible} onMaskClick={()=>{ setVisible(false) }} position='top' 
            bodyStyle={{ height: '10vh',width:'80%',left: '10%',textAlign:'center',lineHeight:'10vh',fontSize:'20px' }}
        >
            验证码为: {verificationCode}
        </Popup>
    </div>
}
export default connect(null,action.base)(Login)